import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterapp/config.dart';
import 'package:flutterapp/models/community.dart';
import 'package:flutterapp/page/utils/dio_http.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/page/widgets/search_bar/index.dart';

class CommunityPickerPage extends StatefulWidget {
  const CommunityPickerPage({
    Key key,
  }) : super(key: key);

  @override
  _CommunityPickerPageState createState() => _CommunityPickerPageState();
}

class _CommunityPickerPageState extends State<CommunityPickerPage> {
  List<Community> commList = [];

  //动态搜索,点击键盘搜索触发方法
  _searchHandle(String value) async {
    //value 是搜索词
    // cityId 是地区id
    var cityId = ScopedModelHelper.getAreaId(context);
    var url = '/hource/community/${value}/${cityId}';

    //发送请求获取小区列表
    var res = await DioHttp.of(context).get(url);
    var data = json.decode(res.toString())['body'];

    List<Community> resdatalist = List<Community>.from(
        data.map((item) => Community.fromJson(item)).toList());

    setState(() {
      commList = resdatalist;
    });
    print(data);
    //print(datalist);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: true,
        title: SearchBarPage(
          showLoaction: false,
          showMap: false,
          onCancel: () {
            //回退
            Navigator.of(context).pop();
          },
          goBackCallback: () {
            Navigator.of(context).pop();
          },
          onSearchSubmit: _searchHandle,
        ),
        backgroundColor: Colors.white,
        //去掉边线
        elevation: 0,
      ),
      body: SafeArea(
        minimum: EdgeInsets.all(10.0),
        child: ListView.separated(
          itemCount: commList.length,
          itemBuilder: (context, index) {
            //返回列表
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                //点击的参数返回的路由(返回一个对象)------------------------------------
                Navigator.of(context).pop(commList[index]);
              },
              child: Container(
                padding: EdgeInsets.all(5.0),
                child: Text(commList[index].name),
              ),
            );
          },
          separatorBuilder: (_context, _) => Divider(),
        ),
      ),
    );
  }
}
